//
//  ConversionController.swift
//  SCA
//
//  Created by tjun on 2025/9/23.
//

import UIKit

class ConversionOptionModel {

    let key: String
    let value: String
    var isSelected: Bool
    var anyVallue: Any?
    
    init(key: String, value: String, isSelected: Bool = false, anyVallue: Any? = nil) {
        self.key = key
        self.value = value
        self.isSelected = isSelected
        self.anyVallue = anyVallue
    }
}

class ConversionController: BaseController {
    
    private var Id: Int
    
    private var scrollView: UIScrollView!
    private var contentView: UIView!
    private var lastView: UIView!
    
    private let ringSizeOptionView = ConversionOptionView(type: .size)
    private let ringTypeOptionView = ConversionOptionView(type: .type)
    private let ringColorOptionView = ConversionOptionView(type: .color)
    private let countryOptionView = ConversionOptionView(type: .country)
    private let phoneNumberOptionView = PhoneNumberOptionView()
    
    private let addressTextField = LabeledTextField()
    private let postalCodeTextField = LabeledTextField()
    private let passwordTextField = LabeledTextField()
    private let confirmButton = MainButton(type: .system, title: "确认".localizedString, font: UIFontMake(16), textColor: .white)
    private var info: ConversionInfo?
    
    
    init(Id: Int) {
        self.Id = Id
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    private func setupUI() {
        
        let topMargin = 8
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: navBarHeight, width: view.width, height: screenHeight - navBarHeight)).addTo(view)
        scrollView.keyboardDismissMode = .onDrag
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.contentInsetAdjustmentBehavior = .never
        
        let contentSize = CGSize(width: scrollView.width, height: scrollView.height)
        
        scrollView.contentSize = contentSize
        
        contentView = UIView().addTo(scrollView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
        
        ringSizeOptionView.addTo(contentView)
        ringSizeOptionView.textLabel.text = "选择".localizedString
        ringSizeOptionView.titleAttributedText = "戒指尺寸*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        ringSizeOptionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
            make.top.equalToSuperview()
            make.height.equalTo(74)
        }
        
        ringTypeOptionView.addTo(contentView)
        ringTypeOptionView.textLabel.text = "选择".localizedString
        ringTypeOptionView.tip = "使用388 USCA兑换限量版".localizedString
        ringTypeOptionView.titleAttributedText = "戒指类型*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        ringTypeOptionView.snp.makeConstraints { make in
            make.left.right.equalTo(ringSizeOptionView)
            make.top.equalTo(ringSizeOptionView.snp.bottom).offset(topMargin)
            make.height.equalTo(96)
        }
        
        ringColorOptionView.addTo(contentView)
        ringColorOptionView.textLabel.text = "选择".localizedString
        ringColorOptionView.titleAttributedText = "戒指颜色*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        ringColorOptionView.snp.makeConstraints { make in
            make.left.right.equalTo(ringSizeOptionView)
            make.top.equalTo(ringTypeOptionView.snp.bottom).offset(topMargin)
            make.height.equalTo(ringSizeOptionView)
        }
        
        countryOptionView.addTo(contentView)
        countryOptionView.textLabel.text = "选择".localizedString
        countryOptionView.titleAttributedText = "国家*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        countryOptionView.snp.makeConstraints { make in
            make.left.right.equalTo(ringSizeOptionView)
            make.top.equalTo(ringColorOptionView.snp.bottom).offset(topMargin)
            make.height.equalTo(ringSizeOptionView)
        }
        
        phoneNumberOptionView.addTo(contentView)
        phoneNumberOptionView.textLabel.text = "选择".localizedString
        phoneNumberOptionView.titleAttributedText = "手机号码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        phoneNumberOptionView.snp.makeConstraints { make in
            make.left.right.equalTo(ringSizeOptionView)
            make.top.equalTo(countryOptionView.snp.bottom).offset(topMargin)
            make.height.equalTo(ringSizeOptionView)
        }
        
        addressTextField.titleAttributedText = "地址*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        addressTextField.textField.keyboardType = .asciiCapable
        addressTextField.addTo(contentView)
        addressTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        addressTextField.snp.makeConstraints { make in
            make.top.equalTo(phoneNumberOptionView.snp.bottom).offset(topMargin)
            make.left.right.equalTo(ringSizeOptionView)
            make.height.equalTo(ringSizeOptionView)
        }
        
        postalCodeTextField.titleAttributedText = "邮政编码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        postalCodeTextField.textField.keyboardType = .asciiCapable
        postalCodeTextField.addTo(contentView)
        postalCodeTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        postalCodeTextField.snp.makeConstraints { make in
            make.top.equalTo(addressTextField.snp.bottom).offset(topMargin)
            make.left.right.equalTo(ringSizeOptionView)
            make.height.equalTo(ringSizeOptionView)
        }
        
        passwordTextField.titleAttributedText = "二级安全密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        passwordTextField.textField.keyboardType = .asciiCapable
        passwordTextField.addTo(contentView)
        passwordTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        passwordTextField.snp.makeConstraints { make in
            make.top.equalTo(postalCodeTextField.snp.bottom).offset(topMargin)
            make.left.right.equalTo(ringSizeOptionView)
            make.height.equalTo(ringSizeOptionView)
        }
        
        
        confirmButton.addTo(contentView)
        //        confirmButton.isEnabled = false
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
        confirmButton.snp.makeConstraints { make in
            make.left.right.equalTo(ringSizeOptionView)
            make.height.equalTo(AppStyle.size.buttonHeight.scaled)
            make.top.equalTo(passwordTextField.snp.bottom).offset(30)
        }
        
        lastView = confirmButton
        
        ringSizeOptionView.addTapGesturesWithTarget(target: self, action: #selector(optionViewTapped(_ :)))
        
        updateContentSize()
        
        loadData()
    }
    
    private func loadData() {
        MineService.loadConversionData(Id: Id) { info in
            self.info = info
            
//            print("info=\(info)")
            
        } failure: { error in
        
        }
    }
    
    @objc func optionViewTapped(_ tap: UITapGestureRecognizer) {
        guard let optionView = tap.view as? ConversionOptionView, let conversionInfo = self.info else { return }
        
        if optionView.type == .size {
            var optionModels: [ConversionOptionModel] = []
            
            let defaultOptionModel = ConversionOptionModel(key: "-1", value: "选择".localizedString)
            if let selectModel = optionView.selectModel {
                if selectModel.key == defaultOptionModel.key {
                    defaultOptionModel.isSelected = true
                }
            } else {
                defaultOptionModel.isSelected = true
            }
            
            optionModels.append(defaultOptionModel)
            
            for sizeModel in conversionInfo.sizeModels {
                
                let model = ConversionOptionModel(key: sizeModel.key, value: sizeModel.value, anyVallue: sizeModel)
                if let selectModel = optionView.selectModel, selectModel.key == model.key {
                    model.isSelected = true
                }
                optionModels.append(model)
            }
            
            ConversionOptionController(datas: optionModels, onSelectOption: { selectOption in
                optionView.selectModel = selectOption
            }).showIn(self)
            return
        }
   
        
    }
    
    @objc func confirmButtonTapped() {
 
    }
    
    @objc func textFieldDidChange(_ sender: UITextField) {
        
        
    }
    
    private func updateContentSize() {
        
        contentView.setNeedsLayout()
        contentView.layoutIfNeeded()
        
        let contentSize = CGSizeMake(view.width, lastView.maxY + 30 + tabBarSafeBottomMargin)
        scrollView.contentSize = contentSize
        contentView.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
    }
    
}


